import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class subarraySum1 {
    /**
     * 和为k的子数组
     * 给你一个整数数组nums和一个整数k，统计返回数组中和为k的子序列
     * 子数组是数组中元素的连续非空序列
     */
    // 注意统计的是连续非空的序列
    public static HashMap<Integer, List<List<Integer>>> method(int[] nums, int k){
        HashMap<Integer, List<List<Integer>>> map = new HashMap<>();
        int pre = 0;
        map.put(0, new ArrayList<>());
        map.get(0).add(new ArrayList<>());

        for(int i = 0; i < nums.length; i++){
            pre += nums[i];
            int diff = pre - k;
            if(map.containsKey(diff)){
                for(List<Integer> list : map.get(diff)){
                    List<Integer> newList = new ArrayList<>(list);
                    newList.add(nums[i]);
                    if(!map.containsKey(pre)){
                        map.put(pre, new ArrayList<>());
                    }
                    map.get(pre).add(newList);
                }
            }

            if(!map.containsKey(pre)){
                map.put(pre, new ArrayList<>());
            }
            map.get(pre).add(new ArrayList<>(List.of(nums[i])));
        }

        return map;
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 4, 5, 3, 6, 5, 4, 7, 8, 6, 5, 4};
        int k = 3;

        HashMap<Integer, List<List<Integer>>> result = method(nums, k);

        for(List<Integer> list : result.get(k)){
            System.out.println(list);
        }
    }
}
